package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @FileName UserServiceImpl
 * @Description
 * @Author Sword
 * @date 2025-10-08
 **/

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用户分页
     *
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Cacheable(cacheNames = UserCacheConstant.PAGE, key = "#userDto.hashCode()")
    @Override
    public PageResponse<UserVo> page(UserDto userDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        Page<UserVo> page = userMapper.page(userDto);

        //获取分页数据
        List<UserVo> userVoList = page.getResult();

        //查询角色ids和labels
        userVoList.forEach(userVo -> {
            Set<String> roleIds = userRoleMapper.getIdsByUserId(userVo.getId());

            Set<String> roleLabels = roleMapper.getLabelsByIds(roleIds);

            userVo.setRoleVoIds(roleIds);
            userVo.setRoleLabels(roleLabels);
        });

        PageResponse<UserVo> userVoPageResponse = PageResponse.of(page, UserVo.class);
        return userVoPageResponse;
    }

    /**
     * 用户列表
     *
     * @param userDto
     * @return
     */
    @Cacheable(cacheNames = UserCacheConstant.LIST, key = "#userDto.hashCode()")
    @Override
    public List<UserVo> list(UserDto userDto) {
        return userMapper.list(userDto);
    }

    /**
     * 用户添加
     *
     * @param userDto
     */
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = UserCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(cacheNames = UserCacheConstant.LIST, allEntries = true)
            }
    )
    @Override
    @Transactional
    public void add(UserDto userDto) {
        //对象拷贝
        User user = BeanUtil.copyProperties(userDto, User.class);

        //生成默认密码
        user.setPassword(BCrypt.hashpw(SuperConstant.DEFAULT_PASSWORD, BCrypt.gensalt()));
        user.setNickName(userDto.getRealName());
        user.setUsername(userDto.getEmail());
        //插入用户信息
        userMapper.insert(user);

        //插入角色信息
        //创建用户角色信息集合
        List<UserRole> userRoleList = new ArrayList<>();
        //获取角色ids封装到UserRole对象中
        userDto.getRoleVoIds().forEach(roleVoId -> {
            UserRole userRole = UserRole.builder()
                    .roleId(Long.valueOf(roleVoId))
                    .userId(user.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            userRoleList.add(userRole);
        });

        userRoleMapper.batchInsert(userRoleList);

    }

    /**
     * 用户修改
     *
     * @param userDto
     */
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = UserCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(cacheNames = UserCacheConstant.LIST, allEntries = true)
            }
    )
    @Override
    @Transactional
    public void updateUser(UserDto userDto) {
        //对象拷贝
        User user = BeanUtil.copyProperties(userDto, User.class);

        user.setNickName(userDto.getRealName());
        user.setUsername(userDto.getEmail());

        //修改用户信息
        userMapper.updateByPrimaryKeySelective(user);

        //删除用户角色信息
        userRoleMapper.deleteByUserId(user.getId());

        //插入角色信息
        //创建用户角色信息集合
        List<UserRole> userRoleList = new ArrayList<>();
        //获取角色ids封装到UserRole对象中
        userDto.getRoleVoIds().forEach(roleVoId -> {
            UserRole userRole = UserRole.builder()
                    .roleId(Long.valueOf(roleVoId))
                    .userId(user.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            userRoleList.add(userRole);
        });

        userRoleMapper.batchInsert(userRoleList);
    }

    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = UserCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(cacheNames = UserCacheConstant.LIST, allEntries = true)
            }
    )
    @Override
    @Transactional
    public void remove(String userIds) {
        //删除用户信息
        userMapper.deleteByPrimaryKey(Long.valueOf(userIds));

        //删除用户角色信息
        userRoleMapper.deleteByUserId(Long.valueOf(userIds));
    }

    /**
     * 启用或禁用用户
     *
     * @param userDto
     */
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = UserCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(cacheNames = UserCacheConstant.LIST, allEntries = true)
            }
    )
    @Override
    public void isEnable(UserDto userDto) {
        User user = BeanUtil.copyProperties(userDto, User.class);

        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 当前用户
     *
     * @return
     */
    @Override
    public UserVo currentUser(Long userId) {
        UserVo userVo = userMapper.currentUser(userId);

        //查询角色ids和labels
        Set<String> RoleIds = userRoleMapper.getIdsByUserId(userId);

        Set<String> labels = roleMapper.getLabelsByIds(RoleIds);

        userVo.setRoleVoIds(RoleIds);
        userVo.setRoleLabels(labels);

        //查询角色Vo集合
        List<RoleVo> roleVoList = roleMapper.listByIds(RoleIds);

        userVo.setRoleList(roleVoList);

        return userVo;
    }

    /**
     * 密码重置
     *
     * @param userId
     */
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = UserCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(cacheNames = UserCacheConstant.LIST, allEntries = true)
            }
    )
    @Override
    public void resetPasswords(Long userId) {
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(userId);

        //生成默认密码
        user.setPassword(BCrypt.hashpw(SuperConstant.DEFAULT_PASSWORD, BCrypt.gensalt()));
        userMapper.updateByPrimaryKeySelective(user);
    }
}
